<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description: 上传方法
 *
 * type: "avatar" "bbs" "goods" "news"
 * extra: "backend" "frontend"
 * size:
 *
 * |- avatar
 *      |- backend
 *      |- frontend
 * |- goods
 *      |- 2016
 *          |- 01
 *      |- 2017
 *
 *
 *
 * @author      Eden
 * @datetime    2016/11/29 22:04
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Upload
{
    private $ci;

    private $config;

    // 错误信息
    private $error = '';

    private $size = 0;

    // ---------------------------
    // 保存路径
    private $savePath = '';
    private $type = '';
    private $oPath = '';    //原图路径,用于生成缩略图
    private $oExt = '';    //
    private $extra = '';
    private $saveFileName = '';

    // ---------------------------

    public function __construct()
    {
        $this->ci = & get_instance();
        $this->ci->config->load('image');
        $this->config = $this->ci->config->item('upload_image');
    }

    /**
     * 设置Extra
     * @param string $extra
     */
    public function setExtra($extra = '')
    {
        $this->extra = $extra;
    }

    /**
     * 获取尺寸限制
     */
    private function _getMaxSize()
    {
        $config =  $this->config[$this->type];
        if (!empty($config['maxSize'])) {
            $this->size = intval($config['maxSize']);
        }
    }

    /**
     * 保存路径
     */
    private function _getSavePath()
    {
        $type = $this->ci->input->get('type');
        $this->type = $type;
        $extra = $this->ci->input->get('extra');
        if (!empty($extra)) {
            $this->extra = $extra;
        }
        $dir = !empty($this->config[$type]) ? $this->config[$type] : '';
        if (!empty($this->extra)) {
            $this->savePath = rtrim(FCPATH, '/') . $dir['path'] . $this->extra . '/';
        } else {
            $this->savePath = rtrim(FCPATH, '/') . $dir['path'] . date('Y/m/');
        }
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function error()
    {
        return $this->error;
    }

    /**
     * 上传操作
     */
    public function upFile($field = 'file')
    {
        $this->_getSavePath();
        $this->_getMaxSize();

        if (!empty($_FILES[$field]) && $this->size !== 0 && $_FILES[$field]['size'] > $this->size) {
            $this->error = '图片尺寸太大';
            return false;
        }

        $result = array();
        $fileName = md5(microtime(true) . uniqid());
        $this->ci->load->library('upload');

        // 保存原图
        $orgPath = $this->savePath . 'o/';
        $this->_checkSavePath($orgPath);
        $config['upload_path'] = $orgPath;
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['file_name'] = $fileName;
        $this->ci->upload->initialize($config);
        $images = array();
        if (!$this->ci->upload->do_upload($field)) {
            $this->error = '上传失败';
            return false;
        } else {
            $data = $this->ci->upload->data();
            $this->oPath = value($data, 'full_path');
            $this->oExt = value($data, 'file_ext');
            $this->saveFileName = value($data, 'file_name');

            $result = array(
                'saveName' => value($data, 'file_name'),
                'imageWidth' => (int) value($data, 'image_width'),
                'imageHeight' => (int) value($data, 'image_height'),
                'imageType' => value($data, 'image_type'),
            );

        }

        // 生成缩略图
        $this->ci->load->library('image_lib');
        foreach($this->config[$this->type]['size'] as $key => $item) {
            $upSavePath = $this->savePath . $key . '/';
            $this->_checkSavePath($upSavePath);
            $config = array();
            if (!empty($item)) {
                $config['source_image'] = $this->oPath;
                $config['create_thumb'] = TRUE;
                $config['maintain_ratio'] = TRUE;
                $config['new_image'] = $upSavePath . $this->saveFileName;
                $config['thumb_marker'] = '';

                if (!empty($item['width']) && !empty($item['height'])) {
                    $config['width'] = intval($item['width']);
                    $config['height'] = intval($item['height']);
                } else if (!empty($item['maxWidth'])) {
                    $config['width'] = intval($item['maxWidth']);
                }

                $this->ci->image_lib->initialize($config);
                $this->ci->image_lib->resize();
            }
        }
        $result = array_merge($result, array('paths' => $this->thumbPath($this->type, $result['saveName'], $this->extra)));
        return $result;
    }

    /**
     * 创建保存路径
     * @param $savePath
     * @return bool
     */
    private function _checkSavePath($savePath)
    {
        if (empty($savePath)) {
            $this->error = '文件路径不可写';
            return false;
        }

        if(!file_exists($savePath) || !is_dir($savePath)) {
            return @mkdir($savePath, 0777, true);
        } else {
            if (is_dir($savePath) && !is_writable($savePath)) {
                return @chmod($savePath, 0777);
            }
        }

        return true;
    }

    /**
     * 获取文件路径数组
     * @param $type
     * @param string $fileName
     * @param string $extra
     * @return array|bool
     */
    public function thumbPath($type, $fileName = '', $extra = '')
    {
        $config = $this->config[$type];
        if (empty($config)) {
            $this->error = '类型错误';
            return false;
        }

        if (empty($fileName)) {
            $this->error = '文件错误';
            return false;
        }

        $path = value($config, 'path');
        $basePath = '/' . trim($path, '/') . '/' . (!empty($extra) ? $extra . '/' : '');
        $sizes = value($config, 'size');

        $save = array();
        if (!empty($sizes) && is_array($sizes)) foreach ($sizes as $k => $size) {
            $save[$k] = $basePath . $k . '/' . $fileName;
        }

        $orgFile = $basePath . 'o/' . $fileName;
        $save['o'] = $orgFile;

        return $save;
    }

    /**
     * 获取大图
     * @param $type
     * @param string $fileName
     * @param string $extra
     * @return string
     */
    public function bigThumb($type, $fileName, $extra = '')
    {
        if (preg_match('/^http/i', $fileName)) {
            return $fileName;
        }

        $config = $this->config[$type];
        if (empty($config)) {
            $this->error = '类型错误';
            return "";
        }

        $path = value($config, 'path');
        $basePath = '/' . trim($path, '/') . '/' . (!empty($extra) ? $extra . '/' : '');
        return $basePath . 'b/' . $fileName;
    }

    /**
     * 带路径的大图
     * @param $type
     * @param $fileName
     * @param string $extra
     * @return string
     */
    public function bigResThumb($type, $fileName, $extra = '')
    {
        if (preg_match('/^http/i', $fileName)) {
            return $fileName;
        }
        $file = $this->bigThumb($type, $fileName, $extra);
        return !empty($file) ? rtrim(base_url(), '/') . $file : '';
    }

    /**
     * 小图
     * @param $type
     * @param $fileName
     * @param string $extra
     * @return bool|string
     */
    public function smallThumb($type, $fileName, $extra = '')
    {
        if (preg_match('/^http/i', $fileName)) {
            return $fileName;
        }

        $config = $this->config[$type];
        if (empty($config)) {
            $this->error = '类型错误';
            return false;
        }

        $path = value($config, 'path');
        $basePath = '/' . trim($path, '/') . '/' . (!empty($extra) ? $extra . '/' : '');
        return $basePath . 's/' . $fileName;
    }

    /**
     * 带路径的小图
     * @param $type
     * @param $fileName
     * @param string $extra
     * @return string
     */
    public function smallResThumb($type, $fileName, $extra = '')
    {
        if (preg_match('/^http/i', $fileName)) {
            return $fileName;
        }
        $file = $this->smallThumb($type, $fileName, $extra);
        return !empty($file) ? rtrim(base_url(), '/') . $file : '';
    }

}
